import { PROJECT_NAME } from '@/app-config'

class Storage {
    constructor({ nameSpace }) {
        this.nameSpace = nameSpace
        this.data = undefined
        this.load()
    }

    save() {
        const { nameSpace, data } = this
        window.localStorage.setItem(nameSpace, JSON.stringify(data))
    }

    load() {
        const data = window.localStorage.getItem(this.nameSpace)
        this.data = data ? JSON.parse(data) : {}
    }

    get(key, newest = true) {
        if (newest) {
            this.load()
        }
        return this.data[key]
    }

    set(key, value) {
        this.data[key] = value
        this.save()
    }

    remove(key) {
        delete this.data[key]
        this.save()
    }
}

const $STORAGE = new Storage({
    nameSpace: PROJECT_NAME,
})

window.$STORAGE = $STORAGE

export default $STORAGE
